'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Layout from '../components/Layout';
import { IconLoader2, IconArrowLeft } from '@tabler/icons-react';

export default function Register() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    name: '',
    age: '',
    gender: 'male',
    height: '',
    weight: '',
    healthGoal: 'maintain',
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      if (formData.password !== formData.confirmPassword) {
        throw new Error('两次输入的密码不一致');
      }

      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.message);

      router.push('/login?message=注册成功，请登录');
    } catch (err) {
      setError(err instanceof Error ? err.message : '注册失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout>
      <div className="max-w-4xl mx-auto">
        <div className="bg-white rounded-lg shadow-sm">
          <div className="p-6">
            <div className="flex items-center gap-4 mb-6">
              <button
                onClick={() => router.back()}
                className="text-gray-600 hover:text-gray-900"
              >
                <IconArrowLeft className="w-5 h-5" />
              </button>
              <h1 className="text-2xl font-bold">创建账号</h1>
            </div>

            {error && (
              <div className="bg-red-50 text-red-600 p-4 rounded-lg mb-6">
                {error}
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="grid md:grid-cols-2 gap-6">
                {/* 基本信息 */}
                <div className="space-y-4">
                  <h2 className="text-lg font-medium mb-4">账号信息</h2>
                  <div>
                    <label className="block text-sm font-medium mb-1">邮箱</label>
                    <input
                      type="email"
                      value={formData.email}
                      onChange={e => setFormData({...formData, email: e.target.value})}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">密码</label>
                    <input
                      type="password"
                      value={formData.password}
                      onChange={e => setFormData({...formData, password: e.target.value})}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">确认密码</label>
                    <input
                      type="password"
                      value={formData.confirmPassword}
                      onChange={e => setFormData({...formData, confirmPassword: e.target.value})}
                      className="input-field w-full"
                      required
                    />
                  </div>
                </div>

                {/* 个人信息 */}
                <div className="space-y-4">
                  <h2 className="text-lg font-medium mb-4">个人信息</h2>
                  <div>
                    <label className="block text-sm font-medium mb-1">姓名</label>
                    <input
                      type="text"
                      value={formData.name}
                      onChange={e => setFormData({...formData, name: e.target.value})}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-1">年龄</label>
                      <input
                        type="number"
                        value={formData.age}
                        onChange={e => setFormData({...formData, age: e.target.value})}
                        className="input-field w-full"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">性别</label>
                      <select
                        value={formData.gender}
                        onChange={e => setFormData({...formData, gender: e.target.value})}
                        className="input-field w-full"
                        required
                      >
                        <option value="male">男</option>
                        <option value="female">女</option>
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-1">身高 (cm)</label>
                      <input
                        type="number"
                        value={formData.height}
                        onChange={e => setFormData({...formData, height: e.target.value})}
                        className="input-field w-full"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">体重 (kg)</label>
                      <input
                        type="number"
                        value={formData.weight}
                        onChange={e => setFormData({...formData, weight: e.target.value})}
                        className="input-field w-full"
                        required
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">健康目标</label>
                    <select
                      value={formData.healthGoal}
                      onChange={e => setFormData({...formData, healthGoal: e.target.value})}
                      className="input-field w-full"
                      required
                    >
                      <option value="lose">减重</option>
                      <option value="maintain">保持健康</option>
                      <option value="gain">增重</option>
                    </select>
                  </div>
                </div>
              </div>

              <div className="flex items-center justify-between pt-4">
                <Link 
                  href="/login"
                  className="text-blue-600 hover:text-blue-700"
                >
                  已有账号？立即登录
                </Link>
                <button
                  type="submit"
                  disabled={loading}
                  className="btn-primary flex items-center gap-2"
                >
                  {loading && <IconLoader2 className="w-4 h-4 animate-spin" />}
                  创建账号
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </Layout>
  );
} 